<template>
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		<el-breadcrumb-item>FM管理</el-breadcrumb-item>
	</el-breadcrumb>

	<!-- 搜索框 -->
	<el-form :inline="true" :model="queryInfo" class="demo-form-inline">
		<el-form-item label="文章名">
			<el-input v-model="queryInfo.title" placeholder="请输入文章名" clearable @clear="queryDataList" />
		</el-form-item>
		<el-form-item label="选择分类">
			<el-select v-model="queryInfo.fmClassifyId" placeholder="请选择分类" clearable @clear="queryDataList">
				<el-option v-for="item in fmClassifyList" :key="item.id" :label="item.classifyName" :value="item.id" />
			</el-select>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" size="large" @click="queryDataList">搜索</el-button>
			<el-button type="primary" size="large" @click="add">新增</el-button>
			<el-button type="danger" size="large" @click="batchremove">批量删除</el-button>
		</el-form-item>
	</el-form>

	<!-- 表格 -->
	<el-table :data="dataList" border style="width: 100%" row-key="id" @selection-change="handleSelectionChange">
		<el-table-column type="selection" width="55" />
		<el-table-column prop="id" label="ID" align="center"></el-table-column>
		<el-table-column prop="title" label="文章名" align="center"></el-table-column>
		<el-table-column prop="briefImageUrl" label="缩略图" width="125px">
			<template #default="scope">
				<!-- 修复：使用briefImageUrl显示图片，支持相对路径拼接 -->
				<el-image style="width: 100px; height: 100px" :src="'http://localhost:8080' + scope.row.briefImageUrl"
					fit="contain" :error="errorImage">
				</el-image>
			</template>
		</el-table-column>



		<el-table-column prop="classify.classifyName" label="所属分类" align="center"></el-table-column>
		<el-table-column label="操作" width="300" align="center">
			<template #default="scope">
				<el-button type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
				<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
			</template>
		</el-table-column>
	</el-table>

	<!-- 分页 -->
	<div class="demo-pagination-block">
		<div class="demonstration"></div>
		<el-pagination v-model:current-page="queryInfo.pageNum" v-model:page-size="queryInfo.pageSize"
			:page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper" :total="total"
			@size-change="handleSizeChange" @current-change="handleCurrentChange" />
	</div>

	<!-- 新增/编辑弹窗 -->
	<el-dialog :title="title1" v-model="dialogFormVisible" width="850" @close="cancle">
		<el-form :model="fmData" label-width="100px">
			<el-form-item label="文章标题">
				<el-input v-model="fmData.title" autocomplete="off" placeholder="文章名"></el-input>
			</el-form-item>
			<el-form-item label="缩略图">
				<el-upload :action="uploadUrl" :on-success="handleUploadSuccess" :show-file-list="false"
					:before-upload="beforeUpload">
					<el-icon style="height: 128px; width: 128px; border: 1px dashed #DCDFE6; color: #DCDFE6;">
						<Plus />
					</el-icon>
				</el-upload>
				<!-- 显示已上传的图片预览 -->
				<el-image v-if="fmData.briefImageUrl" style="width: 128px; height: 128px; margin-top: 10px"
					:src="'http://localhost:8080' + fmData.briefImageUrl" fit="contain" :error="errorImage">
				</el-image>
			</el-form-item>
			<el-form-item label="所属分类">
				<el-select v-model="fmData.fmClassifyId" placeholder="请选择分类">
					<el-option v-for="item in fmClassifyList" :key="item.id" :label="item.classifyName"
						:value="item.id" />
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="cancle">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup>
	import {
		reactive,
		ref,
		getCurrentInstance,
		onMounted
	} from 'vue';
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus';
	import {
		Plus
	} from '@element-plus/icons-vue';

	// 错误图片占位符（图片加载失败时显示）
	const errorImage = 'https://cube.elemecdn.com/e/fd/0fc7d205a56d3ab76e2af7b54b73.jpeg';

	// 上传相关配置
	const uploadUrl = ref('http://localhost:8080/upload'); // 后端上传接口地址

	// 表格数据与分页
	const total = ref(0);
	const dataList = ref([]);
	const queryInfo = reactive({
		title: '',
		fmClassifyId: '',
		pageNum: 1,
		pageSize: 5
	});

	// 分类列表
	const fmClassifyList = ref([]);

	// 弹窗与表单数据
	const dialogFormVisible = ref(false);
	const title1 = ref('');
	const fmData = reactive({
		id: '',
		title: '',
		fmClassifyId: '',
		briefImageUrl: '' // 存储图片路径
	});

	// 批量选择的数据
	const multipleSelection = ref([]);

	// 获取全局axios
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;

	// 查询数据列表
	const queryDataList = () => {
		axios.get('fm/page', {
			params: queryInfo
		}).then((resp) => {
			if (resp.code === 200) {
				dataList.value = resp.data.list || [];
				total.value = resp.data.total || 0;
			} else {
				ElMessage.error('查询失败：' + resp.message);
			}
		}).catch(err => {
			ElMessage.error('网络错误，请重试');
		});
	};

	// 查询分类列表
	const queryfmClassifyList = () => {
		axios.get('fmclassify').then((resp) => {
			if (resp.code === 200) {
				fmClassifyList.value = resp.data || [];
			} else {
				ElMessage.error('分类查询失败：' + resp.message);
			}
		}).catch(err => {
			ElMessage.error('分类加载失败');
		});
	};

	// 分页事件
	const handleSizeChange = (val) => {
		queryInfo.pageSize = val;
		queryDataList();
	};
	const handleCurrentChange = (val) => {
		queryInfo.pageNum = val;
		queryDataList();
	};

	// 新增
	const add = () => {
		title1.value = '新增';
		// 重置表单
		Object.assign(fmData, {
			id: '',
			title: '',
			fmClassifyId: '',
			briefImageUrl: ''
		});
		dialogFormVisible.value = true;
	};

	// 编辑
	const edit = (row) => {
		title1.value = '编辑';
		// 复制行数据到表单（深拷贝避免双向绑定问题）
		Object.assign(fmData, JSON.parse(JSON.stringify(row)));
		dialogFormVisible.value = true;
	};

	// 取消
	const cancle = () => {
		dialogFormVisible.value = false;
	};

	// 确认提交（新增/编辑）
	const confirm = () => {
		// 简单校验
		if (!fmData.title) {
			return ElMessage.warning('请输入文章标题');
		}
		if (!fmData.fmClassifyId) {
			return ElMessage.warning('请选择所属分类');
		}

		// 提交请求
		const request = fmData.id ?
			axios.put('fm', fmData) // 编辑：PUT请求
			:
			axios.post('fm', fmData); // 新增：POST请求

		request.then(resp => {
			if (resp.code === 200) {
				ElMessage.success(fmData.id ? '修改成功' : '新增成功');
				dialogFormVisible.value = false;
				queryDataList(); // 重新加载列表
			} else {
				ElMessage.error((fmData.id ? '修改' : '新增') + '失败：' + resp.message);
			}
		}).catch(err => {
			ElMessage.error('提交失败，请重试');
		});
	};

	// 删除
	const remove = (id) => {
		ElMessageBox.confirm('此操作将永久删除该数据，是否继续？', '警告', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			axios.delete(`fm/${id}`).then(resp => {
				if (resp.code === 200) {
					ElMessage.success('删除成功');
					queryDataList();
				} else {
					ElMessage.error('删除失败：' + resp.message);
				}
			}).catch(err => {
				ElMessage.error('删除失败，请重试');
			});
		}).catch(() => {
			ElMessage.info('已取消删除');
		});
	};

	// 批量删除
	const batchremove = () => {
		if (multipleSelection.value.length === 0) {
			return ElMessage.warning('请选择要删除的数据');
		}
		ElMessageBox.confirm(`确定要删除选中的${multipleSelection.value.length}条数据吗？`, '警告', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			axios.delete('fm', {
				params: {
					ids: multipleSelection.value.join(',')
				}
			}).then(resp => {
				if (resp.code === 200) {
					ElMessage.success('批量删除成功');
					queryDataList();
				} else {
					ElMessage.error('批量删除失败：' + resp.message);
				}
			}).catch(err => {
				ElMessage.error('删除失败，请重试');
			});
		}).catch(() => {
			ElMessage.info('已取消删除');
		});
	};

	// 监听选择事件
	const handleSelectionChange = (val) => {
		multipleSelection.value = val.map(item => item.id);
	};

	// 上传前校验
	const beforeUpload = (file) => {
		const isImage = file.type.startsWith('image/');
		const isLt2M = file.size / 1024 / 1024 < 2; // 限制2MB以内

		if (!isImage) {
			ElMessage.error('只能上传图片文件！');
		}
		if (!isLt2M) {
			ElMessage.error('图片大小不能超过2MB！');
		}
		return isImage && isLt2M; // 只有满足条件才允许上传
	};

	// 上传成功回调
	const handleUploadSuccess = (response) => {
		if (response.code === 200) {
			// 假设后端返回格式：{ code:200, data: { filePath: '/upload/xxx.jpg' } }
			fmData.briefImageUrl = response.data.filePath;
			ElMessage.success('图片上传成功');
		} else {
			ElMessage.error('图片上传失败：' + (response.message || '未知错误'));
		}
	};

	// 初始化
	onMounted(() => {
		queryDataList();
		queryfmClassifyList();
	});
</script>

<style scoped>
	.el-breadcrumb {
		margin-bottom: 15px;
		padding: 0 0 15px;
		border-bottom: 1px solid #ddd;
	}

	.demo-form-inline .el-input,
	.demo-form-inline .el-select {
		width: 220px;
		margin-right: 10px;
	}

	.demo-pagination-block {
		margin-top: 15px;
		text-align: right;
	}

	.el-table {
		margin-top: 15px;
		line-height: 40px;
	}

	/* 新语法（推荐） */
	:deep(.el-upload) {
		display: inline-block;
	}
</style>